package com.hrh.selectsystem.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hrh.selectsystem.aop.MyJwtInterceptor;
import com.hrh.selectsystem.common.BaseResponse;
import com.hrh.selectsystem.common.ErrorCode;
import com.hrh.selectsystem.common.ResultUtils;
import com.hrh.selectsystem.exception.BusinessException;
import com.hrh.selectsystem.exception.ThrowUtils;
import com.hrh.selectsystem.model.dto.matchResult.MatchRecordAddRequest;
import com.hrh.selectsystem.model.dto.mentor.MentorLoginRequest;
import com.hrh.selectsystem.model.dto.mentor.MentorUpdatePasswordRequest;
import com.hrh.selectsystem.model.dto.student.StudentQueryRequest;
import com.hrh.selectsystem.model.entity.Mentor;
import com.hrh.selectsystem.model.entity.Student;
import com.hrh.selectsystem.model.vo.mentor.LoginMentorVO;
import com.hrh.selectsystem.model.vo.mentor.MentorByTokenVO;
import com.hrh.selectsystem.model.vo.mentor.MentorVO;
import com.hrh.selectsystem.model.vo.student.StudentByMentorVO;
import com.hrh.selectsystem.model.vo.student.StudentVO;
import com.hrh.selectsystem.service.ChoiceRecordService;
import com.hrh.selectsystem.service.MatchResultService;
import com.hrh.selectsystem.service.MentorService;
import com.hrh.selectsystem.service.StudentService;
import com.hrh.selectsystem.service.impl.MentorServiceImpl;
import com.hrh.selectsystem.service.impl.StudentServiceImpl;
import com.hrh.selectsystem.utils.JwtTokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static com.hrh.selectsystem.service.impl.MentorServiceImpl.SALT;

/**
 * 导师接口
 *
 * @author hrh
 * 
 */
@RestController
@RequestMapping("/mentor")
@Api(tags = "导师接口")
@Slf4j
public class MentorController {

    @Resource
    private MentorService mentorService;
    @Resource
    private StudentService studentService;
    @Resource
    private MatchResultService matchResultService;

    /**
     * 导师登录
     *
     * @param mentorLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "导师登录")
    public BaseResponse<LoginMentorVO> mentorLogin(@RequestBody MentorLoginRequest mentorLoginRequest, HttpServletRequest request) {
        if (mentorLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String mentorAccount = mentorLoginRequest.getMentoraccount();
        String mentorPassword = mentorLoginRequest.getMentorpassword();
        String encryptPassword = DigestUtils.md5DigestAsHex((StudentServiceImpl.SALT + mentorPassword).getBytes());
        if (StringUtils.isAnyBlank(mentorAccount, mentorPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        LoginMentorVO loginMentorVO = mentorService.mentorLogin(mentorAccount, mentorPassword, request);
        String userrole = "mentor";
        //登录成功后，生成jwt令牌
        String token = JwtTokenUtils.getToken(
                loginMentorVO.getId().toString(),
                encryptPassword,
                userrole
        );
        loginMentorVO.setToken(token);
        return ResultUtils.success(loginMentorVO);
    }

    /**
     * 根据token获取导师信息
     * @param request
     * @return
     */
    @GetMapping("/token")
    @ApiOperation(value = "根据token获取导师信息(无role)")
    public BaseResponse<MentorByTokenVO> getTokenMentor(HttpServletRequest request) {
        String token = request.getHeader("token");
        String userId = MyJwtInterceptor.getUserIdFromToken(token);
        Mentor mentor = mentorService.getById(userId);
        if (mentor == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        MentorByTokenVO mentorByTokenVO = new MentorByTokenVO();
        BeanUtils.copyProperties(mentor, mentorByTokenVO);
        return ResultUtils.success(mentorByTokenVO);
    }

    /**
     * 获取当前登录导师信息
     *
     * @param request
     * @return
     */
    @GetMapping("/get-user")
    @ApiOperation(value = "获取当前登录导师信息")
    public BaseResponse<MentorVO> getMentorById(HttpServletRequest request) {
        Mentor mentor = mentorService.getLoginMentor(request);
        MentorVO mentorVO = mentorService.getMentorVO(mentor);
        return ResultUtils.success(mentorVO);
    }

    
    /**
     * 导师注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation(value = "导师注销")
    public BaseResponse<Boolean> mentorLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = mentorService.mentorLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 导师修改个人密码
     *
     * @param mentorUpdatePasswordRequest
     * @param request
     * @return
     */
    @PostMapping("/update-password")
    @ApiOperation(value = "导师修改个人密码")
    public BaseResponse<Boolean> updateMyMentor(@RequestBody MentorUpdatePasswordRequest mentorUpdatePasswordRequest,
                                              HttpServletRequest request) {
        try {
            if (mentorUpdatePasswordRequest == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR);
            }
            String oldPassword = mentorUpdatePasswordRequest.getOldpassword();
            String encryptOldPassword = DigestUtils.md5DigestAsHex((MentorServiceImpl.SALT + oldPassword).getBytes());
            if (!encryptOldPassword.equals(mentorService.getById(mentorService.getLoginMentor(request).getId()).getMentorpassword())){
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "旧密码错误");
            }
            //小于6位，不符合规范
            if (mentorUpdatePasswordRequest.getMentorpassword().length() < 6) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "新密码长度小于6位，不符合规范");
            }
            Mentor loginMentor = mentorService.getLoginMentor(request);
            Mentor mentor = new Mentor();
            BeanUtils.copyProperties(mentorUpdatePasswordRequest, mentor);
            mentor.setId(loginMentor.getId());
            mentor.setMentorpassword(DigestUtils.md5DigestAsHex((SALT + mentor.getMentorpassword()).getBytes()));
            boolean result = mentorService.updateById(mentor);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
            return ResultUtils.success(true);
        } catch (Exception e) {
            return ResultUtils.success(false);
        }
    }

    /**
     * 导师获取学生申请列表
     * @param studentQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/apply")
    @ApiOperation(value = "导师获取学生申请列表")
    public BaseResponse<Page<StudentByMentorVO>> listApplyStudents(@RequestBody StudentQueryRequest studentQueryRequest, HttpServletRequest request) {
        long current = studentQueryRequest.getCurrent();
        long size = studentQueryRequest.getPageSize();
        Mentor mentor = mentorService.getLoginMentor(request);
        // 获取当前导师下的学生列表
        List<StudentByMentorVO> studentVOList = studentService.listApplyStudents(mentor);
        // 封装分页对象
        Page<StudentByMentorVO> studentPage = new Page<>(current, size, studentVOList.size());
        studentPage.setRecords(studentVOList);
        return ResultUtils.success(studentPage);
    }

    /**
     * 导师提交选择信息
     * @param matchRecordAddList
     * @param request
     * @return
     */
    @PostMapping("/submit-choice")
    @ApiOperation(value = "导师提交选择信息")
    public BaseResponse<Boolean> submitChoice(@RequestBody List<MatchRecordAddRequest> matchRecordAddList, HttpServletRequest request) {
        try {
            if (matchRecordAddList == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR);
            }
            // 获取当前导师id
            Mentor mentor = mentorService.getLoginMentor(request);
            Long mentorId = mentor.getId();

            // 获取当前轮次
            Integer roundNumber = studentService.getStartedRound();

            // 交选择信息
            boolean result = matchResultService.submitChoice(matchRecordAddList, mentorId, roundNumber);
            return ResultUtils.success(result);
        } catch (Exception e) {
            return ResultUtils.success(false);
        }
    }

    /**
     * 导师分页获取和自己匹配成功的学生列表
     * @param studentQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/success")
    @ApiOperation(value = "导师分页获取和自己匹配成功的学生列表")
    public BaseResponse<Page<StudentByMentorVO>> listSuccessStudents(@RequestBody StudentQueryRequest studentQueryRequest, HttpServletRequest request) {
        long current = studentQueryRequest.getCurrent();
        long size = studentQueryRequest.getPageSize();
        Mentor mentor = mentorService.getLoginMentor(request);

        // 获取当前导师下的学生列表
        List<StudentByMentorVO> studentVOList = studentService.listSuccessStudents(mentor);

        // 封装分页对象
        Page<StudentByMentorVO> studentPage = new Page<>(current, size, studentVOList.size());
        studentPage.setRecords(studentVOList);

        return ResultUtils.success(studentPage);
    }
}
